<template>
  <div class="update">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="资源描述" prop="des">
        <el-input type="textarea" v-model="ruleForm.des"></el-input>
      </el-form-item>
      <el-form-item label="所属分类" prop="cagory">
        <el-select v-model="ruleForm.cagory" placeholder="请选择所属分类">
          <el-option v-for="item in category" :key="item.id" :label="item.categoryname" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="path">
        <el-upload
          class="upload-demo"
          drag
          action="api/UploadServlet"
          :multiple="false"
          :show-file-list="true"
          :file-list="fileList"
          :on-change="handleUploadChange"
          :before-upload="beforeUpload"
          with-credentials
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
              <div>将文件拖到此处，或<em>点击上传</em></div>
              <div style="color:#ccc;font-size:12px;">只能上传txt、xml、xls、docx、pdf、rar、zip、xlsx等格式的文件</div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即上传</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 上传文件的列表
      fileList: [],
      ruleForm: {
        name: "",
        des: "",
        cagory: "",
        path:''
      },
      rules: {
        name: [
          { required: true, message: "请输入资源名称", trigger: "blur" },
          { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" },
        ],
        des: [
          { required: true, message: "请输入资源描述", trigger: "blur" },
          {
            min: 20,
            max: 100,
            message: "长度在20-100个字符以内",
            trigger: "blur",
          },
        ],
        cagory: [
          { required: true, message: "请选择所属分类", trigger: "change" },
        ],
      },
      CpostData: {
        pageNo: "1",
        pageSize: "5",
        categroy: "allin",
      },
      category:[],
      path:''
    };
  },
  computed:{
    user(){
      if(sessionStorage.getItem("user")){
        this.$store.commit("setUserObj",JSON.parse(sessionStorage.getItem("user")))
      }else{
        this.$store.commit("setUserObj",null)
      }
      return this.$store.state.userObj
    }
  },
  methods: {
    beforeUpload(file) {
      const fileType = file.name.substring(file.name.lastIndexOf("."));
      console.log("文件类型",fileType)
      if (
        fileType.toLowerCase() != ".txt" &&
        fileType.toLowerCase() != ".xml" &&
        fileType.toLowerCase() != ".xls" &&
        fileType.toLowerCase() != ".docx" &&
        fileType.toLowerCase() != ".pdf" &&
        fileType.toLowerCase() != ".rar" &&
        fileType.toLowerCase() != ".zip" &&
        fileType.toLowerCase() != ".xlsx" &&
        fileType.toLowerCase() != ".doc"
      ) {
        this.$message.error("文件格式不正确");
        this.fileList = [];
        return false;
      }
    },
    // 覆盖element的默认上传文件
    // uploadHttpRequest(data) {
    //   let reader = new FileReader();
    //   let that = this;
    //   reader.readAsText(data.file);
    //   console.log("上传文件",data.file)
    //   reader.onload = function () {
    //     // that.formData.mmiapXml = this.result;
        
    //   };
    // },
    // 限制文件上传的个数只有一个，获取上传列表的最后一个
    handleUploadChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; // 这一步，是 展示最后一次选择的文件
        if(this.fileList[0].response){
          this.ruleForm.path = this.fileList[0].response.data
        }
        
        console.log("文件",this.user)
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = {
            userid:this.user.id,
            userName:this.user.nickname,
            name: this.ruleForm.name,
            des: this.ruleForm.des,
            cagory: this.ruleForm.cagory,
            path:this.ruleForm.path

          }
          this.API.addFile(obj).then(res=>{
            if(res.message.code == 200){
              this.ruleForm.name = ''
              this.ruleForm.des = ''
              this.ruleForm.cagory = ''
              this.fileList = []
              this.$message({
                message: res.message.msg,
                type: "success",
              });
            }else{
              this.$message.error(res.message.msg);
            }
          })
        } else {
          console.log("error submit!!");
          this.$message.error("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getCagory(){
      this.API.getCategoryList(this.CpostData).then(res=>{
        if(res.message.code == 200){
          this.category = res.data.pageData||[]
        }
      })
    }
  },
  mounted(){
    this.getCagory()
  }
};
</script>

<style lang="less" scoped>
.update{
    width:800px;
    margin:20px auto;
}
</style>